import type { NextPage } from "next";
import { Fragment, useEffect, useRef, useState } from "react";
import styled, { css } from "styled-components";
import HeadPortrait from "../src/components/HeadPortrait";
import FriendsList from "../src/components/Home/FriendsList";
import OnLinePeopleCount from "../src/components/Home/OnLinePeopleCount";
import RequestList from "../src/components/Home/RequestList";
import TemporaryDialogue from "../src/components/Home/TemporaryDialogue";
import SEOHeader from "../src/components/SEO";
import WorldNews from "../src/components/WorldNews";
import { useAuth } from "../src/context/AuthProvide";
import { LoadProcess } from "../src/helper";
import { UserInfo } from "../src/hook/useRegisterForm";
import { otherUserList } from "../src/meta/helper/OtherUser";
import { acterWrap } from "../src/meta/object";
import { partsControl } from "../src/meta/PartsControl";
import { init } from "../src/meta/script";
import { SocketManager } from "../src/socket";
import { flexCenter } from "../src/styled";
import { FixedBtnCss } from "../src/styled/help";

const Home: NextPage = () => {
    const { isLogin, user } = useAuth();
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const [isLoadedScene, setIsLoadedScene] = useState(false);
    const [loaded, setLoaded] = useState(0);

    /**
     * 创建socket连接
     */
    useEffect(() => {
        // init({
        //     antialias: true,
        //     canvas: canvasRef.current!,
        // });

        SocketManager.success(function () {
            SocketManager.emit("getOnlineCount");
        }).init();

        LoadProcess.onCanShow(() => {
            setLoaded(0.5);
        });

        return () => {
            SocketManager.disconnect();
            init.clear();
        };
    }, []);

    /**
     * 用户登录后 加载场景
     */
    useEffect(() => {
        if (user._id && !isLoadedScene) {
            if (!canvasRef.current) throw Error("获取canvas失败");
            init(
                {
                    antialias: true,
                    canvas: canvasRef.current!,
                },
                () => {
                    setLoaded(1);
                }
            );
            setIsLoadedScene(true);
            partsControl.init(user._id);
        }
    }, [user._id, isLoadedScene]);

    return (
        <Container>
            <SEOHeader title={process.env.NEXT_PUBLIC_TITLE} />
            <HeadPortrait />
            <WorldNews />
            {isLogin ? (
                <Fragment>
                    <TemporaryDialogue />
                    <RequestList />
                    <TopicsBtn onClick={() => window.open(`${location.href}topics`)}>话题</TopicsBtn>
                    <CustomProfile onClick={() => window.open(`${location.href}CustomProfile?id=${user._id}`)}>
                        自定义形象
                    </CustomProfile>
                    <FriendsList user={user as UserInfo} />
                </Fragment>
            ) : null}
            <CanvasBox>
                {isLoadedScene ? <Loading loaded={loaded}>loading..</Loading> : null}
                <canvas ref={canvasRef}></canvas>
            </CanvasBox>
            <OnLinePeopleCount />
        </Container>
    );
};

export default Home;

const Loading = styled.div<{ loaded: number }>`
    color: #1a9a06;
    position: fixed;
    top: 0;
    left: 0;
    background: #0a4102;
    ${flexCenter};
    width: 100vw;
    height: 100vh;
    transition: all 0.3s linear;
    opacity: ${({ loaded }) => 1 - loaded};
    z-index: ${({ loaded }) => (loaded == 1 ? -1 : 10)};
`;

const CanvasBox = styled.div`
    --color: #206a11;
    position: fixed;
    width: 100vw;
    height: 100vh;
    right: 0;
    bottom: 0;
    border: 0vw solid var(--color);
    transition: all 0.3s linear;
    z-index: 10;
    opacity: 1;
    cursor: pointer;
    canvas {
        width: 100% !important;
        height: 100% !important;
    }
`;

const Container = styled.div``;

export const CustomProfile = styled.span`
    ${FixedBtnCss}
`;

const TopicsBtn = styled(CustomProfile)`
    bottom: 15vmax;
    right: 1vmax;
`;
